#include "ZPackageBase.h"
#include "XML\ZXml.h"


void ZPackageFactory::InitStringCode()
{
//	QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
//	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GBK"));
}

ZPackageBase* ZPackageFactory::CreatePackage(const QByteArray& byteArr)
{
	QString sXmlStr = QString::fromUtf8(byteArr.data(), byteArr.size());
//	QString sXmlStr(byteArr);
	ZXmlDoc xmlDoc;
	xmlDoc.InitLoadFrom(sXmlStr);
	QString sClassName = xmlDoc.GetRootElem().attribute(PackageClassAttr);
	ZPackageBase* pPackage = dynamic_cast<ZPackageBase*>(ZDynObject::CreateObjFromName(sClassName));
	if (pPackage)
	{
		pPackage->LoadByXml(xmlDoc);
	}

	Q_ASSERT(pPackage);
	return pPackage;
}

QByteArray ZPackageFactory::GetAllTotalData( const ZPackageBase& package )
{
//	QByteArray dataByteArr = GetAllXmlStr(package).toUtf8();
	QByteArray dataByteArr = package.GetXmlStr().toUtf8();
	QByteArray totalData;
	qint64 iDataLen = sizeof(qint64) + dataByteArr.size();
	totalData.append((char*)(&iDataLen), sizeof(qint64));
	totalData.append(dataByteArr);
	return totalData;
}

// QString ZPackageFactory::GetAllXmlStr( const ZPackageBase& package )
// {
// 	QString packXmlStr = package.GetXmlStr();
// 	ZXmlDoc xmlDoc;
// 	xmlDoc.InitLoadFrom(packXmlStr);
// 	xmlDoc.GetRootElem().setAttribute(PackageClassAttr, package.GetClassName_Z());
// 	return xmlDoc.GetXmlStr();
// }
//////////////////////////////////////////////////////////////////////////
ZImplementDynCreate(ZPackage_Str)

ZPackage_Str::ZPackage_Str( const QString& sStr )
{
	m_sStr = sStr;
}

QString ZPackage_Str::GetXmlStr() const
{
	ZXmlDoc xmlDoc;
	xmlDoc.InitSaveTo();
	xmlDoc.AppendChild(xmlDoc.GetRootElem(), tr("strVal"), m_sStr);
	return xmlDoc.GetXmlStr(GetClassName_Z());
}

void ZPackage_Str::LoadByXml(ZXmlDoc& xmlDoc)
{
	QDomElement rootElem = xmlDoc.GetRootElem();
	QDomElement elem = rootElem.firstChild().toElement();
	xmlDoc.GetVal(elem, m_sStr);
}

//////////////////////////////////////////////////////////////////////////
ZImplementDynCreate(ZPackage_ByteArr)

void ZPackage_ByteArr::SetByteArr( const QByteArray& byteArray )
{
	m_byteArr = byteArray;
}

const QByteArray& ZPackage_ByteArr::GetByteArr() const
{
	return m_byteArr;
}

QString ZPackage_ByteArr::GetXmlStr() const
{
	ZXmlDoc xmlDoc;
	xmlDoc.InitSaveTo();
	xmlDoc.AppendChild(xmlDoc.GetRootElem(), tr("byteArrVal"), m_byteArr);
	return xmlDoc.GetXmlStr(GetClassName_Z());
}

void ZPackage_ByteArr::LoadByXml(ZXmlDoc& xmlDoc)
{
	QDomElement rootElem = xmlDoc.GetRootElem();
	QDomElement elem = rootElem.firstChild().toElement();
	xmlDoc.GetVal(elem, m_byteArr);
}
